import json
from datetime import datetime

from django.contrib.auth.models import User
from django.core.cache import cache
from django.core.paginator import Paginator
from django.forms import model_to_dict
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from baseinfo.helpfun import query_to_list, defect_filter, defect_to_excelpath
from defect.models import Defect


def hello(request):
    return HttpResponse("hello test")

# 新增缺陷
def add_defect(request):
    if request.method == 'POST':
        data = json.loads(request.body)
        outage = data.get('outage')
        main_order = data.get('main_order').strip()
        order_detail = data.get('order_detail').strip()
        defect_detail = data.get('defect_detail').strip()
        defect_order = data.get('defect_order').strip()
        equipment = data.get('equipment').strip()
        defect_date = data.get('defect_date')
        deal_department = data.get('deal_department').strip().upper()
        team = data.get('team')
        defect = Defect.objects.filter(defect_order=defect_order)
        if defect.exists():
            res = {
                'data': None,
                'meta': {'status': 801, 'message': '此缺陷通知单在系统中已经存在！'}
            }
            return JsonResponse(res)
        new_defect = Defect()
        new_defect.outage = outage
        new_defect.main_order = main_order
        new_defect.order_detail = order_detail
        new_defect.defect_detail = defect_detail
        new_defect.defect_order = defect_order
        new_defect.equipment = equipment
        new_defect.defect_date = datetime.strptime(defect_date, '%Y-%m-%d').date()
        new_defect.deal_department = deal_department
        new_defect.equipment = equipment
        new_defect.team = team
        token = request.META.get('HTTP_AUTHORIZATION')
        user_id = cache.get(token)
        user = User.objects.filter(pk=user_id)[0]
        new_defect.create_user = user
        new_defect.save()
        res = {
            'data': None,
            'meta': {'status': 200, 'message': '添加缺陷信息成功！'}
        }
        return JsonResponse(res)

# 根据查询条件获取经验反馈
def get_defect(request):
    if request.method == 'GET':
        queryInfo = request.GET
        pagesize = int(queryInfo.get('pagesize'))
        pagenum = int(queryInfo.get('pagenum'))
        defects = defect_filter(queryInfo)
        total = defects.count()
        if total:
            paginator = Paginator(defects, pagesize)
            num_pages = paginator.num_pages
            if pagenum > num_pages:
                pagenum = 1
            page_defects = paginator.page(pagenum)
            res = {
                'data': {'total': total, 'page_defects': query_to_list(page_defects), 'pagenum': pagenum},
                'meta': {'status': 200, 'message': "获取缺陷数据成功"}
            }
        else:
            res = {
                'data': {},
                'meta': {'status': 201, 'message': "未查询到相关缺陷信息"}
            }
        return JsonResponse(res)

# 根据id删除缺陷
def delete_defect(request, defect_id):
    if request.method == 'DELETE':
        try:
            defect = Defect.objects.get(pk=defect_id)
            defect.is_delete = True
            defect.save()
            res = {
                'data': None,
                'meta': {'status': 200, 'message': '删除缺陷信息成功！'}
            }
        except Exception as e:
            res = {
                'data': None,
                'meta': {'status': 802, 'message': '删除缺陷信息失败,请联系管理员！'}
            }
        return JsonResponse(res)

# 根据id编辑缺陷
def edit_defect(request, defect_id):
    if request.method == 'GET':
        defect = Defect.objects.get(pk=defect_id)
        res = {
            'data': {'defect': model_to_dict(defect)},
            'meta': {'status': 200, 'message': '获取待编辑的缺陷信息成功'}
        }
        return JsonResponse(res)
    elif request.method == 'PUT':
        data = json.loads(request.body)
        # print(data)
        defect = Defect.objects.get(pk=defect_id)
        defect.outage = data.get('outage')
        defect.main_order = data.get('main_order')
        defect.order_detail = data.get('order_detail')
        defect.defect_detail = data.get('defect_detail')
        defect.equipment = data.get('equipment')
        defect.defect_order = data.get('defect_order')
        defect.defect_date = datetime.strptime(data.get('defect_date'), '%Y-%m-%d').date()
        defect.deal_department = data.get('deal_department')
        defect.team = data.get('team')
        defect.is_concerned = data.get('is_concerned')
        if data.get('deal_order'):
            defect.deal_order = data.get('deal_order')
        if data.get('deal_detail'):
            defect.deal_detail = data.get('deal_detail')
        if data.get('is_closed'):
            defect.is_closed = data.get('is_closed')
            if data.get('closed_date'):
                defect.closed_date = datetime.strptime(data.get('closed_date'), '%Y-%m-%d').date()
            else:
                defect.closed_date = datetime.today()
        else:
            defect.is_closed = data.get('is_closed')
            defect.closed_date = None
        defect.save()

        res = {
            'data': {'defect': model_to_dict(defect)},
            'meta': {'status': 200, 'message': '缺陷信息修改成功'}
        }
        return JsonResponse(res)

# 导出缺陷的excel
def export_excel(request):
    if request.method == 'GET':
        queryInfo = request.GET
        defects = defect_filter(queryInfo)
        excel_url = defect_to_excelpath(defects)
        res = {
            'data': {'excel_url': excel_url},
            'meta': {'status': 200, 'message': '获取缺陷统计表链接成功！'}
        }
        return JsonResponse(res)